<template>
  <div class="system-setting">

    <div id="sysSettingForm" class="sysSettingForm">
      <base-form :checkAll="checkAll" :isAutoUpload="true" :form="formState" @uploadFinished="uploadFinished"
        @onCheckAllCheckbox="onCheckAllCheckbox" @upload_remove_Finished='upload_remove_Finished' @getIndex="getIndex"
        @onChangeSelect="changeSelect" ref="getbaseForm">
        <template #ipTable="{ section_index, formItem_index }">

          <div v-if="formState.ipPrams" style="margin: 16px 0;display:flex; align-items:center" class="editIp">
            <a-form-item-rest>
              <span>
                {{ formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] }}.
                <a-input-number v-model:value="ip1"
                  v-if="[172, 10].includes(formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1])"
                  style="width: 58px;px;height:28px"
                  :min="formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] == '172' ? 16 : 0"
                  :max="formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] == '172' ? 31 : 255" />
                {{ [172,
                  10].includes(formState.formState[section_index].children[formItem_index].options[formState.ipPrams -
                    1]) ? '.' : '' }}
                <a-input-number v-model:value="ip3" style="width: 58px;px;height:28px" min="0" max="255" />.
                <a-input-number v-model:value="ip4" style="width:58px;height:28px" min="0" max="255" />
              </span>
              <span style="margin:0 8px"> - </span>
              <span>
                {{ formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] }}.
                <a-input-number v-model:value="ip2"
                  v-if="[172, 10].includes(formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1])"
                  style="width: 58px;px;height:28px"
                  :min="formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] == '172' ? 16 : 0"
                  :max="formState.formState[section_index].children[formItem_index].options[formState.ipPrams - 1] == '172' ? 31 : 255" />
                {{ [172,
                  10].includes(formState.formState[section_index].children[formItem_index].options[formState.ipPrams -
                    1]) ? '.' : '' }}
                <a-input-number v-model:value="ip5" style="width:58px;height:28px" min="0" max="255" />.
                <a-input-number v-model:value="ip6" style="width:58px;height:28px" min="0" max="255" />
              </span>
            </a-form-item-rest>
            <a-button style=" margin-left: 24px;height:28px; padding:2px 16px"
              :disabled="!formState.formState[section_index].children[formItem_index].param"
              @click="addItem(section_index, formItem_index)" type="primary">添加</a-button>
          </div>
          <baseTable :columns="columns.whileBlockColumns"
            :dataSource="ipsData.records.filter((item: any) => item.param == formState.ipCtlType)" :isSelect="true"
            :scroll="scroll" :rowSelection="1" ref="tagBaseTables">
            <template #bodyCell="{ column, text, record, index }">
              <template v-if="column.dataIndex === 'startIp'">
                <div class="editable-cell">
                  <div v-if="record.isEdit" class="editable-cell-input-wrapper">
                    <a-form-item-rest>
                      <span v-if="record.startIp.split('.')[0] == 192">
                        {{ record.startIp.split('.')[0] }}.{{ record.startIp.split('.')[1] }}.
                      </span>
                      <span v-else>
                        {{ record.startIp.split('.')[0] }}.
                        <a-input-number v-model:value="editIp1" style="width: 58px;px;height:28px"
                          :min="record.startIp.split('.')[0] == '172' ? 16 : 0"
                          :max="record.startIp.split('.')[0] == '172' ? 31 : 255" />.
                      </span>

                      <a-input-number v-model:value="editIp2" style="width: 58px;px;height:28px" min="0" max="255" />.
                      <a-input-number v-model:value="editIp3" style="width:58px;height:28px" min="0" max="255" />
                    </a-form-item-rest>

                  </div>
                  <div v-else class="editable-cell-text-wrapper">
                    {{ record.startIp }}
                  </div>
                </div>
              </template>
              <template v-if="column.dataIndex === 'endIp'">
                <div class="editable-cell">
                  <div v-if="record.isEdit" class="editable-cell-input-wrapper">
                    <a-form-item-rest>
                      <div v-if="record.isEdit" class="editable-cell-input-wrapper">
                        <span v-if="record.endIp.split('.')[0] == 192">
                          {{ record.endIp.split('.')[0] }}.{{ record.endIp.split('.')[1] }}.
                        </span>
                        <span v-else>
                          {{ record.endIp.split('.')[0] }}.
                          <a-input-number v-model:value="editIp4" style="width: 58px;px;height:28px"
                            :min="record.endIp.split('.')[0] == '172' ? 16 : 0"
                            :max="record.endIp.split('.')[0] == '172' ? 31 : 255" />.
                        </span>

                        <a-input-number v-model:value="editIp5" style="width: 58px;px;height:28px" min="0" max="255" />.
                        <a-input-number v-model:value="editIp6" style="width:58px;height:28px" min="0" max="255" />
                      </div>
                    </a-form-item-rest>

                  </div>
                  <div v-else class="editable-cell-text-wrapper">
                    {{ record.endIp }}
                  </div>
                </div>
              </template>
              <template v-if="column.dataIndex === 'oparation'">
                <a @click="toEdit(record.id)" style="margin-right: 8px;" v-if="!record.isEdit">编辑</a>
                <a @click="saveEdit(record.id)" style="margin-right: 8px;" v-else>保存</a>
                <a-popconfirm placement="topRight" @confirm="confirmIpListDelete(record.id)">
                  <template #title>
                    <p style="width: 197px">
                      删除此ip后，内容处也同时删除
                    </p>
                  </template>
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </template>
            <!-- <template #otherOpration>
            <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
              :disabled="!rowSelection.length">删除</a-button></template> -->
          </baseTable>

        </template>

      </base-form>
      <div class="ips-container" v-if="formState.autoInterceptEnable">
        <span>当前被拦截IP:</span>
        <div>
          <baseTable :columns="columns.cutipColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
            ref="tagBaseTables" :isShowPagination="isShowPagination" :total="configData.total" @changePage="changePage">
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.ellipsis">
                <table-tool-tip :text="text" :column="column"></table-tool-tip>
              </template>
              <template v-if="column.dataIndex === 'oparation'">
                <a-popconfirm placement="topRight" @confirm="confirmDelete(record)">
                  <template #title>
                    <p style="width: 197px">
                      删除此ip后，内容处也同时删除
                    </p>
                  </template>
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </template>
            <!-- <template #otherOpration>
            <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
              :disabled="!rowSelection.length">删除</a-button></template> -->
          </baseTable>
        </div>

      </div>
    </div>
    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="btnPerm" @click="saveButton">保存</a-button>
    </div>
  </div>
</template>
      

<script lang="ts" setup>
import { ref, UnwrapRef, reactive, watch, onMounted } from "vue";
import { dataSourceType, detailDataItemType } from "@/type.d";
import baseTable from "@/components/table/baseTable.vue";
import { sysSettingForm } from './formCofig';
import { cloneDeep } from 'lodash'
import columns from "@/components/table/tableConfig/columnsName";
import baseForm from '@/components/form/newBaseForm.vue'
import request from "@/api/index"
import { message } from "ant-design-vue";
import { scrollType, modeProp } from "@/type.d";
import { useFixeWidth, styleWidth } from '@/hooks/useFixeWidth';
import { routerPerm, randomWord } from '@/utils/common';
// props
const props = defineProps({
  extendInfo: {
    type: Object,
    default: {}
  },
  id: {
    type: Number,
    default: 1
  }
})
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
// data
const editableData: UnwrapRef<Record<string, dataSourceType>> = reactive({});
const ip1 = ref<number>();
const ip2 = ref<number>();
const ip3 = ref<number>(0);
const ip4 = ref<number>(0);
const ip5 = ref<number>(0);
const ip6 = ref<number>(0);
const editIp1 = ref<number>();
const editIp2 = ref<number>();
const editIp3 = ref<number>(0);
const editIp4 = ref<number>(0);
const editIp5 = ref<number>(0);
const editIp6 = ref<number>(0);
const checkAll = ref<boolean>(true)

const isShowPagination = true; // 是否需要配分页器
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let ipsData = reactive<configDataType>({ total: 0, size: 10, records: [] });
let datas = reactive({})
const sysSettingInfo = ref<detailDataItemType>([])
const formState = ref<(dataSourceType)>(sysSettingForm);
console.log(formState, 'formState');
const sectionIndex = ref<(number)>(0);
const deleteArr = ref<(string | number)[]>([]);
const ipWhitelist = ref<dataSourceType[]>([]);
const ipBlacklist = ref<dataSourceType[]>([]);
const formItemIndex = ref<(number)>(0);
const id = ref<(number)>(0);
const getbaseForm = ref();
const postData = ref()
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const btnPerm = ref<boolean>(false)
//watch
watch(() => formState.value, (newVal, oldVal) => {
  postData.value = cloneDeep(newVal)
}, { deep: true })

watch(() => formState.value.ipCtlType, (newVal, oldVal) => {
  formState.value.ipPrams = undefined;

}, { deep: true })
watch(() => formState.value.accessHour, (newVal, oldVal) => {
  checkAll.value = newVal.length === formState.value.formState[1].children[0].checkboxOptions.length;
})
watch(() => ipsData.records, (newVal, oldVal) => {
  ipWhitelist.value = [];
  ipBlacklist.value = [];
  newVal.forEach((item: dataSourceType) => {
    if (item.param == '2') {
      ipWhitelist.value.push({ startIp: item.startIp, endIp: item.endIp })
    }
    if (item.param == '3') {
      ipBlacklist.value.push({ startIp: item.startIp, endIp: item.endIp })
    }
  })
}, { deep: true })

//methods

const onCheckAllCheckbox = (param: string) => {
  checkAll.value = !checkAll.value
  formState.value[param] = checkAll.value ? formState.value.formState[1].children[0].checkboxOptions : []
}

const toEdit = (id: number | string) => {
  let index: number = 0;
  ipsData.records.forEach((item: any, idx: number) => {
    item.isEdit = false;
    if (item.id == id) {
      index = idx;
    }
  })
  ipsData.records[index].isEdit = true;
  let startIp = ipsData.records[index].startIp;
  let endIp = ipsData.records[index].endIp;

  if (['172', '10'].includes(startIp.split('.')[0])) {
    editIp1.value = startIp.split('.')[1];
    editIp2.value = startIp.split('.')[2];
    editIp3.value = startIp.split('.')[3];
    editIp4.value = endIp.split('.')[1];
    editIp5.value = endIp.split('.')[2];
    editIp6.value = endIp.split('.')[3];
  } else {
    editIp2.value = startIp.split('.')[2];
    editIp3.value = startIp.split('.')[3];
    editIp5.value = endIp.split('.')[2];
    editIp6.value = startIp.split('.')[3];
  }

};
const saveEdit = (id: number | string) => {
  let index: number = 0;
  ipsData.records.forEach((item: any, idx: number) => {
    item.isEdit = false;
    if (item.id == id) {
      index = idx;
    }
  })
  let startIp = ipsData.records[index].startIp;
  let endIp = ipsData.records[index].endIp;
  if (startIp.split('.')[0] == 172 || startIp.split('.')[0] == 10) {
    ipsData.records[index].startIp = startIp.split('.')[0] + '.' + editIp1.value + '.' + editIp2.value + '.' + editIp3.value;
    ipsData.records[index].endIp = endIp.split('.')[0] + '.' + editIp4.value + '.' + editIp5.value + '.' + editIp6.value;
  } else {
    ipsData.records[index].startIp = startIp.split('.')[0] + '.' + startIp.split('.')[1] + '.' + editIp2.value + '.' + editIp3.value;
    ipsData.records[index].endIp = endIp.split('.')[0] + '.' + endIp.split('.')[1] + '.' + editIp5.value + '.' + editIp6.value;
  }
  ipsData.records[index].isEdit = false;
}
//添加黑白名单
const addItem = (index1: number, index2: number) => {
  let start = formState.value.formState[index1].children[index2].options[formState.value.ipPrams - 1];
  let end = formState.value.formState[index1].children[index2].options[formState.value.ipPrams - 1]
  if (start == 172 || start == 10) {
    start = start + '.' + ip1.value;
    end = end + '.' + ip2.value;
  }
  let obj = {
    startIp: start + '.' + ip3.value + '.' + ip4.value,
    endIp: start + '.' + ip5.value + '.' + ip6.value,
    isEdit: false,
    id: randomWord(false, 4, 4),
    param: formState.value.ipCtlType,
  }
  ipsData.records.push(obj);
  ip3.value = 0;
  ip4.value = 0;
  ip5.value = 0;
  ip6.value = 0;
}

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize
  }
}

const confirmDelete = async (item: any) => {// 删除单个ip
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value)
};
const confirmIpListDelete = async (id: number | string) => {// 删除单个ip
  let index: number = 0;
  ipsData.records.forEach((item: any, idx: number) => {
    item.isEdit = false;
    if (item.id == id) {
      index = idx;
    }
  })
  ipsData.records.splice(index, 1)
};
const deleteRecords = async (keys: (string | number)[] = []) => { // 调接口删除ip
  await request.fetchContentTagDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      message.success(res.message);
      fetchFirewallData()
    } else {
      message.error(res.message);
    }
  });
}
// 获取index
const getIndex = (section_index: number, formItem_index: number,) => {
  sectionIndex.value = section_index;
  formItemIndex.value = formItem_index;
}

// 上传图片返回值
const uploadFinished = (data: any) => {
  formState.value[sectionIndex.value].children[formItemIndex.value].value.splice(0, 1);
  formState.value[sectionIndex.value].children[formItemIndex.value].value.push(data[0]);
  formState.value[sectionIndex.value].children[formItemIndex.value].picId = data[0].id;
}

// 删除图片
const upload_remove_Finished = (data: any) => {
  setTimeout(() => {
    formState.value[sectionIndex.value].children[formItemIndex.value].value.splice(0, 1);
    getbaseForm.value.baseForm.validate([sectionIndex.value, 'children', formItemIndex.value, 'value']).then((res: any) => {
    })
  }, 10);
}
//保存数据
const saveButton = () => {
  postData.value.accessWeek = formState.value.accessWeek;
  postData.value.accessHour = formState.value.accessHour;
  postData.value.domainBlacklist = formState.value.domainBlacklist.length && formState.value.domainBlacklist.split(/[\n,]/g) || [];
  postData.value.autoInterceptEnable = formState.value.autoInterceptEnable
  postData.value.id = id.value
  postData.value.invalidHour = postData.value.invalidHour ? postData.value.invalidHour : 0

  postData.value.ipBlacklist = ipBlacklist.value;
  postData.value.ipWhitelist = ipWhitelist.value;
  delete postData.value.formState
  if (postData.value.ipCtlType == 2 && !postData.value.ipWhitelist.length) {
    message.error('请在表格里填写并勾选ip段！');
    return
  }
  if (postData.value.ipCtlType == 3 && !postData.value.ipBlacklist.length) {
    message.error('请在表格里填写并勾选ip段！');
    return
  }
  getbaseForm.value.baseForm.validate().then(() => {
    request.fetchFirewallSaveOrUpdate(postData.value).then((res: dataSourceType) => {
      if (res.code === '00000 00000') {
        fetchFirewallData()
        message.success(res.message)
      } else {
        message.error(res.message)
      }
    }).catch((err: any) => {
      message.error(err)
    });
  })
}
//选择ip
const changeSelect = (section_index: any, formItem_index: any, formItem: any) => {
  console.log(formState.value.ipPrams, 'section_index,formItem_index,')
  let value = formState.value.formState[section_index].children[formItem_index].options[formState.value.ipPrams - 1];
  console.log(value, 'value')
  if (value == 172) {
    ip1.value = 16;
    ip2.value = 16;
  } else if (value == 10) {
    ip1.value = 0;
    ip2.value = 0;
  }
}

//获取详情内容
const fetchFirewallData = async () => {
  request.fetchFirewallData({}).then((res: dataSourceType | any) => {
    id.value = res.id
    ipsData.records = formState.value.ipCtlType == 2 ? res.ipWhitelist : res.ipBlacklist || []
    ipWhitelist.value = res.ipWhitelist
    ipBlacklist.value = res.ipBlacklist
    if (res.ipCtlType == 2) {
      configData.records = res.ipBlacklist || [];
    } else if (res.ipCtlType == 3) {
      configData.records = res.ipWhitelist || [];
    }
    formState.value.accessWeek = res.accessWeek || [];
    formState.value.accessHour = res.accessHour || [];
    formState.value.domainBlacklist = res.domainBlacklist?.join('\n') || [];
    formState.value.autoInterceptEnable = res.autoInterceptEnable;
    formState.value.ipCtlType = res.ipCtlType;
    formState.value.invalidHour = res.invalidHour;
  });
}

const startTime = () => {
  formState.value['accessHour'] = formState.value.formState[1].children[0].checkboxOptions
}
//onMounted
onMounted(() => {
  routerPerm().includes('saveAble') ? btnPerm.value = false : btnPerm.value = true;
  fetchFirewallData()
  useFixeWidth()
  startTime()
})
</script>
<style lang="less" scoped>
.system-setting {
  padding-left: 16px;
  height: 100%;
  background-color: #fff;
  width: 100%;
  height: calc(100% - 120px);
  padding-bottom: 56px;

  .sysSettingForm {
    height: 100%;
    overflow-y: auto;
  }

  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    z-index: 10;
    background: #fff;
  }
}

::v-deep(.ant-table-cell:nth-last-of-type(1)) {
  text-align: right;
}

.ips-container {
  display: flex;
  flex-direction: row;

  span {
    width: 99px;
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
    line-height: 14px;
    margin-left: 134px;
    margin-top: 9px;
    text-align: right;
  }

}

::v-deep(.baseForm .ant-form-item .ant-select) {
  display: block;
}

::v-deep(.ips-container .ant-table-wrapper) {
  margin-left: 12px;
}

::v-deep(.ant-table-wrapper) {
  width: 740px;
  margin-top: 8px;
}
</style>
<style lang="less">
#sysSettingForm {

  .ant-form-item-label {
    text-align: right;
    width: 196px;
    margin-right: 8px;
  }

  .editIp {
    .ant-input-number-input {
      height: 28px;
    }
  }
}

#form_item_accessHour {
  .ant-checkbox-wrapper {
    width: 62px;
  }


}
</style>